package be.donovan.gui.helper.components;

import java.awt.Component;
import java.awt.Container;
import java.util.HashSet;
import java.util.Observable;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.swingx.JXTable;


public class JXTableRegistry extends Observable {

	private static Set<JXTable> registry = new HashSet<JXTable>();

	private static Log logger = LogFactory.getLog(JXTableRegistry.class);

	public static void register(JXTable table) {
		registry.add(table);
		logger.info("register : " + table);
	}

	public static void unregister(ViewI view) {
		unregister((Container) view);
		logger.info("unregistered : " + view);
	}

	private static void unregister(Container container) {
		for (Component component : container.getComponents()) {
			if (component instanceof Container) {
				unregister((Container) component);
			} else {
				if (component instanceof JXTable) {
					registry.remove(component);
				}
			}
		}
	}

	public static Set<JXTable> getTablesOf(ViewI view) {
		return getTablesOf((Container) view);
	}

	private static Set<JXTable> getTablesOf(Container container) {
		Set<JXTable> result = new HashSet<JXTable>();
		for (Component component : container.getComponents()) {
			if (component instanceof Container) {
				result.addAll(getTablesOf((Container) component));
			}
			if (component instanceof JXTable) {
				result.add((JXTable) component);
			}
		}
		result.addAll(registry);
		return result;
	}
}
